package com.opennice.soukaoti.learngo.user.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.opennice.soukaoti.dao.BaseDAO;
import com.opennice.soukaoti.learngo.user.dao.IUserDAO;
import com.opennice.soukaoti.vo.LearngoUser;

public class UserDAO extends BaseDAO implements IUserDAO {

	@Override
	public List browseLearngoUser() {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		String hql = "from LearngoUser as m";
		Query query = session.createQuery(hql);
		List<LearngoUser> list = query.list();
		tx.commit();
		session.close();
		return list;
	}

	@Override
	public LearngoUser loadLearngoUser(Integer userId) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		LearngoUser user = (LearngoUser) session.load(LearngoUser.class, userId);
		tx.commit();
		session.close();
		return user;
	}

	@Override
	public void saveLearngoUser(LearngoUser user) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();

	}

	@Override
	public LearngoUser searchLearngoUserByEmail(String email) {
			Session session = getSession();
			Transaction tx = session.beginTransaction();
			String hql = "from LearngoUser as m where m.userEmail=:email";
			Query query = session.createQuery(hql);
			query.setString("email", email);
			List<LearngoUser> list = query.list();
			tx.commit();
			session.close();
			if(list.size()==1){
				return list.get(0);
			}
	      return null;
	}

	@Override
	public void updateLearngoUser(LearngoUser user) {
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		session.close();
	}
	public void deleteLearngoUser(LearngoUser user){
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.delete(user);
		tx.commit();
		session.close();
	}

}
